<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\model\v1\AdminLog;
use app\api\model\v1\Users;
use app\api\validate\v1\LoginValidate;
use app\api\validate\v1\UserValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\Request;

class User extends BaseController
{
    /**
     * @User: 刘海龙
     * @Date: 2021/11/10
     * @Time: 9:39
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 微信用户
     */
    public function wechatList()
    {
        //获取每页显示的条数
        $limit = $this->request->param('limit', 10);
        $map = [];
        if ($this->request->has('username') && !empty($this->request->param('username'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('username') . '%'];
        }
        if ($this->request->has('mobile') && !empty($this->request->param('mobile'))) {
            $map[] = ['mobile', 'like', '%' . $this->request->param('mobile') . '%'];
        }
        $data = Users::where($map)->paginate($limit);
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/26
     * @Time: 10:16
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增微信前端用户
     */
    public function wechatSave()
    {

        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                UserValidate::rules($id),
                UserValidate::msg());
            if ($validator) {
                $data = $this->request->except(['password_confirm']);
                if (empty($data['unit_id'])) {
                    $data['unit_id'] = 0;
                }
                if (intval($id) === 0) {
                    $data['password'] = password_hash(!empty($data['password']) ? $data['password'] : '111111', PASSWORD_DEFAULT);
                    $data['create_id'] = $this->request->uid ?? 0;
                    Users::create($data);
                } else {
                    if (empty($data['password'])) {
                        unset($data['password']);
                    } else {
                        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                    }
                    $user = Users::find($id);
                    $user->update($data);
                }
                AdminLog::record(intval($id) === 0 ? '新增前端用户' : '编辑前端用户', $this->request->param(), $this->request->uid, $this->request->username);
                //添加用户角色中间表信息
                //GroupUserPivot::roleUserSave($user,$this->request->param('role_id'));
                return $this->response();
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }


    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/26
     * @Time: 10:27
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除用户
     */
    public function wechatDelete($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $user = Users::find($id);
            if (is_null($user)) {
                return $this->response(404, '此用户不存在');
            }
            //->force()
            $user->delete();
            AdminLog::record('删除前端用户', $this->request->param(), $this->request->uid, $this->request->username);
        }
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/11/12
     * @Time: 9:02
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 微信登录
     */
    public function wxLogin()
    {
        $data = $this->request->param();
        try {
            $this->validate(['mobile' => $data['mobile'], 'password' => $data['password']], LoginValidate::class);
            if (!$user = Users::where('mobile', $data['mobile'])->find()) {
                return $this->response(403, '用户名不存在');
            }
            if (!password_verify($data['password'], $user->password)) {
                return $this->response(403, '密码错误');
            }
            $token = $this->token->createToken($user->id);
            $user->token = $token;
            $user->login_time = time();
            $user->save();

        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
        return $this->response($user);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * lhl 2021/12/10
     */
    public function selectUserAllList(){
        $res = Users::select();
        return $this->response($res);
    }
}
